package com.example.thridhero.broadcastbestpractice;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by thridHero on 2017/3/29.
 */

public class BaseActivity extends AppCompatActivity {
    private FroceOffLineReiver froceOffLineReiver;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.thridhero.broadcastbestpractice.LOGOUT");
        froceOffLineReiver = new FroceOffLineReiver();
        registerReceiver(froceOffLineReiver,intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (froceOffLineReiver != null){
            unregisterReceiver(froceOffLineReiver);
            froceOffLineReiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.removeActivity(this);
    }
}
class FroceOffLineReiver extends BroadcastReceiver{

    @Override
    public void onReceive(final Context context, Intent intent) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("警告！");
        builder.setMessage("您在其他其他地方登陆了，请重新登陆");
        builder.setCancelable(false);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityManager.finishAll();
                Intent intent = new Intent(context,MainActivity.class);
                context.startActivity(intent);
            }
        });
        builder.show();
    }
}